package serie03;

import java.util.LinkedList;

public class StdHistory<E> implements History<E> {
	
	// ATTRIBUTS
	
	private LinkedList<E> list;
	private int maxHeight;
	private int currentPosition;
	private int endPosition;
	
	// CONSTRUCTEURS
	
	public StdHistory(int maxHeight) {
		if (maxHeight <= 0) {
			throw new IllegalArgumentException("Taille négative");
		}
		this.maxHeight = maxHeight;
		currentPosition = -1;
		endPosition = -1;
		list = new LinkedList<E>();
	}
	
	// REQUETES
	
	public int getMaxHeight() {
		return maxHeight;
	}
	
	public int getCurrentPosition() {
		return currentPosition;
	}
	
	public E getCurrentElement() {
		if (getCurrentPosition() <= -1) {
			throw new IllegalStateException("Début de pile");
		}
		return list.get(currentPosition);
	}
	
	public int getEndPosition() {
		return endPosition;
	}
	
	// COMMANDES
	
	public void add(E e) {
		if (e == null) {
			throw new IllegalArgumentException("Mauvais élément");
		}
		if (getCurrentPosition() != getMaxHeight() - 1) {
			currentPosition += 1;
			if (getCurrentPosition() < getEndPosition()) {
				// on supprime les elements du dessus
				list.set(getCurrentPosition(), e);
			} else {
				list.add(getCurrentPosition(), e);
			}
			endPosition = getCurrentPosition();
		} else {
			list.removeFirst();
			list.add(getMaxHeight() - 1, e);
		}
	}
	
	public void goForward() {
		if (getCurrentPosition() >= getEndPosition()) {
			throw new IllegalArgumentException("Mauvaise position");
		}
		currentPosition += 1;
	}
	
	public void goBackward() {
		if (getCurrentPosition() <= -1) {
			throw new IllegalArgumentException("Mauvaise position courante");
		}
		currentPosition -= 1;
	}

}
